package com.gosling.cloudspace.aop;

import cn.hutool.core.date.StopWatch;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validation;
import java.util.ArrayList;
import java.util.List;


@Aspect
@Component
public class ApiPrintAspect {
    private static final Logger log = LoggerFactory.getLogger(ApiPrintAspect.class);

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void getRequestMapping() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void getGetMapping() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void getPostMapping() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.ExceptionHandler)")
    public void exceptionHandler() {
    }

    /**
     * 打印范围可自行增加，目前采集已知常用的接口映射注解
     * 打印日志级别可自定义修改
     *
     * @param point
     * @return
     */
    @Around("getRequestMapping() || getGetMapping() || getPostMapping() || exceptionHandler()")
    public Object printApiLog(ProceedingJoinPoint point) throws Throwable {
        StopWatch stopWatch = new StopWatch("LOG");
        stopWatch.start();
        Object[] args = point.getArgs();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        log.info("请求IP: {},请求路径: {},请求方式: {},方法描述: {}",
                request.getRemoteAddr(),
                request.getRequestURL(),
                request.getMethod(),
                getParameter(args));
        Object retVal = point.proceed(args);
        stopWatch.stop();
        log.info("接口耗时: {} ms ,应答报文: {}", stopWatch.getLastTaskTimeMillis(), JSONObject.toJSONString(retVal));
        return retVal;
    }

    private String getParameter(Object[] args) {
        List<String> params = new ArrayList<>();
        for (Object obj : args) {
            if (obj instanceof HttpServletResponse) {
                continue;
            }
            if (obj instanceof HttpServletRequest) {
                continue;
            }
            if (obj instanceof MultipartFile) {
                continue;
            }
            if (obj instanceof BindingResult) {
                continue;
            }
            if (obj instanceof Validation) {
                continue;
            }
            if (obj instanceof Exception) {
                continue;
            }
            params.add(JSON.toJSONString(obj));
        }
        return params.toString();
    }

    private String paramsByReader(HttpServletRequest request) {
        if (request instanceof ContentCachingRequestWrapper) {
            return new String(((ContentCachingRequestWrapper) request).getContentAsByteArray());
        }
        return null;
    }
}
